package com.spzx.test.t11;

import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomUtils;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CookRoom {

    Lock lock = new ReentrantLock();

    Condition cookLock = lock.newCondition();
    Condition cutLock = lock.newCondition();
    Condition giveLock = lock.newCondition();

    String foodStatus = "cut";

    @SneakyThrows
    public void cut() {
        lock.lock();
        try {
            while(!foodStatus.equals("cut")){
                cutLock.await();
            }
            System.out.println(Thread.currentThread().getName()+"正在切菜");
            TimeUnit.SECONDS.sleep(RandomUtils.nextInt(1,5));
            System.out.println(Thread.currentThread().getName()+"切菜完毕，唤醒炒菜线程");
            foodStatus = "cook";
            cookLock.signal();
        } finally {
            lock.unlock();
        }
    }

    @SneakyThrows
    public void cook() {
        lock.lock();
        try {
            while(!foodStatus.equals("cook")){
                cookLock.await();
            }
            System.out.println(Thread.currentThread().getName()+"正在炒菜");
            TimeUnit.SECONDS.sleep(RandomUtils.nextInt(1,5));
            System.out.println(Thread.currentThread().getName()+"炒菜完毕，唤醒上菜线程");
            foodStatus = "give";
            giveLock.signal();
        } finally {
            lock.unlock();
        }
    }

    @SneakyThrows
    public void give() {
        lock.lock();
        try {
            while(!foodStatus.equals("give")){
                giveLock.await();
            }
            System.out.println(Thread.currentThread().getName()+"正在端菜");
            TimeUnit.SECONDS.sleep(RandomUtils.nextInt(1,5));
            System.out.println(Thread.currentThread().getName()+"上菜完毕，下一道！切菜线程");
            foodStatus = "cut";
            cutLock.signal();
        } finally {
            lock.unlock();
        }
    }
}
